/*
 * @(#)SafeUserController.java 2019年9月24日 下午12:19:42
 * Copyright 2019 zmr, Inc. All rights reserved. 
 * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.dev.web.controller.safe;

import com.dev.bbs.bean.BbsSignInfo;
import com.dev.bbs.domain.BbsUser;
import com.dev.bbs.form.UserForm;
import com.dev.bbs.service.IBbsUserService;
import com.dev.bbs.service.IBbsUserSignService;
import com.dev.common.annotation.Log;
import com.dev.common.config.Global;
import com.dev.common.constant.ShiroConstants;
import com.dev.common.core.controller.BaseController;
import com.dev.common.core.domain.AjaxResult;
import com.dev.common.enums.BusinessType;
import com.dev.common.utils.file.FileUploadUtils;
import com.dev.framework.shiro.service.BbsPasswordService;
import com.dev.framework.util.ShiroUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>File：SafeUserController.java</p>
 * <p>Title: </p>
 * <p>Description:</p>
 * <p>Copyright: Copyright (c) 2019 2019年9月24日 下午12:19:42</p>
 * <p>Company: yinrunnet.com </p>
 * @author 张孟如
 * @version 1.0
 */
@Controller
@RequestMapping("safe/user")
public class SafeUserController extends BaseController
{
    private static final Logger log    = LoggerFactory.getLogger(SafeUserController.class);

    private String              prefix = "safe/user";

    @Autowired
    private IBbsUserSignService bbsUserSignService;

    @Autowired
    private IBbsUserService     bbsUserService;

    @Autowired
    private BbsPasswordService  passwordService;

    @GetMapping()
    public String index(Model model)
    {
        BbsUser user = ShiroUtils.getBbsUser();
        BbsSignInfo sign = null;
        if (user != null)
        {
            sign = bbsUserSignService.getSign(user.getUserId());
        }
        else
        {
            // 未登录
            sign = new BbsSignInfo();
        }
        model.addAttribute("sign", sign);
        model.addAttribute("user", user);
        return prefix + "/index";
    }

    /**
     * 我的帖子
     * @return
     * @author zmr
     */
    @GetMapping("post")
    public String post()
    {
        return prefix + "/post";
    }

    @GetMapping("setting")
    public String setting(Model model)
    {
        long userId = ShiroUtils.getUserId();
        BbsUser bbsUser = bbsUserService.getUserWithInfoById(userId);
        model.addAttribute("bbsUser", bbsUser);
        return prefix + "/setting";
    }

    @PostMapping("info/edit")
    @ResponseBody
    public AjaxResult updateInfo(@Validated(value = UserForm.UserInfoGroup.class) UserForm userForm,
            HttpServletRequest request)
    {
        BbsUser bbsUser = ShiroUtils.getBbsUser();
        if ((!bbsUser.getNickname().equals(userForm.getNickname()))
                && bbsUserService.checkNicknameExist(userForm.getNickname()))
        {
            return error("昵称已经存在");
        }
        if (bbsUserService.updateUserInfo(userForm, bbsUser) > 0)
        {
            bbsUser = bbsUserService.selectBbsUserById(bbsUser.getUserId());
            request.getSession().setAttribute(ShiroConstants.CURRENT_USER, bbsUser);
            ShiroUtils.setBbsUser(bbsUser);
            return success();
        }
        return error("更新失败");
    }

    /**
     * 修改密码
     * @param userForm
     * @param request
     * @return
     * @author zmr
     */
    @Log(title = "修改密码", businessType = BusinessType.UPDATE)
    @PostMapping("repass")
    @ResponseBody
    public AjaxResult repass(@Validated(value = UserForm.RepassGroup.class) UserForm userForm,
            HttpServletRequest request)
    {
        BbsUser bbsUser = ShiroUtils.getBbsUser();
        if (!passwordService.matches(bbsUser, userForm.getNowpass()))
        {
            return error("密码验证错误");
        }
        bbsUser.setSalt(ShiroUtils.randomSalt());
        bbsUser.setPassword(
                passwordService.encryptPassword(bbsUser.getUsername(), userForm.getNewpass(), bbsUser.getSalt()));
        if (bbsUserService.resetUserPwd(bbsUser) > 0)
        {
            ShiroUtils.setBbsUser(bbsUserService.selectBbsUserById(bbsUser.getUserId()));
            return success();
        }
        return error();
    }

    @GetMapping("message")
    public String message()
    {
        return prefix + "/message";
    }

    @PostMapping("avatar")
    @ResponseBody
    public AjaxResult avatar(@RequestParam(value = "avatar", required = true) String avatar)
    {
        BbsUser user=new BbsUser().setUserId(ShiroUtils.getUserId()).setAvatar(avatar);
        if (bbsUserService.updateBbsUser(user)> 0)
        {
            BbsUser  bbsUser=bbsUserService.selectBbsUserById(user.getUserId());
            ShiroUtils.setBbsUser(bbsUser);
            ShiroUtils.getSession().setAttribute(ShiroConstants.CURRENT_USER, bbsUser);
            return success();
        }
        return error();
    }

    /**
     * 保存头像
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult updateAvatar(@RequestParam("file") MultipartFile file)
    {
        BbsUser user = ShiroUtils.getBbsUser();
        try
        {
            if (!file.isEmpty())
            {
                String avatar = FileUploadUtils.upload(Global.getAvatarPath(), file);
                user.setAvatar(avatar);
                if (bbsUserService.updateBbsUser(user) > 0)
                {
                    ShiroUtils.setBbsUser(bbsUserService.selectBbsUserById(user.getUserId()));
                    return success();
                }
            }
            return error();
        }
        catch (Exception e)
        {
            log.error("修改头像失败！", e);
            return error(e.getMessage());
        }
    }
}
